<template>
	<Page>
		<Topbar hideMenu @scanCode="scanCode" />
		<Content>
			<Panel>
				<view class="left">
					<Info hideCuttingPlan :data="workInfo" backUrl="/pages/workbench/material/index" />
				</view>
				<view class="right">
					<view class="tab_box">
						<view>
							<view :class="['tab_btn', { active: active === item}]"
								v-for="(item, index) in ['投料', '退料', '料头料尾']" :key="index" @click="tabClick(item)">
								{{ item }}
							</view>
						</view>
					</view>
					<view class="content_box">
						<FormWrap header :headerBorder="false" title="班次信息">
							<u--form labelPosition="left" :model="model" :rules="rules" :ref="`uForm`"
								labelWidth="12rem ">
								<u-row justify="space-between">
									<u-col span="5"><u-form-item label="班次时间" prop="shiftTime" required
											class="label-fwn">
											<DatePicker v-model="model.shiftTime" @change="shiftTimeChange" />
										</u-form-item></u-col>
									<u-col span="6"><u-form-item label="班次" prop="shiftId" required class="label-fwn">
											<SingleSelect @change="shiftChange" v-model="model.shiftId" :list="shifts"
												mode="single" />
										</u-form-item></u-col>
								</u-row>
							</u--form>
							<CheckBoxPanelGroup title="物料选择" v-model="list1" ref="checkboxPanelGroup" bodyHeight="60vh">
								<template slot-scope="{ list, item, index }">
									<FormWrap>
										<u--form labelPosition="left" :model="item" :rules="rules"
											:ref="`uForm${item.id}`" labelWidth="16rem ">
											<u-form-item label="物料编号" class="form-item-6rem">
												{{ item.materialCode || '--' }}
											</u-form-item>
											<u-form-item label="物料名称" class="label-fwn form-item-6rem">
												{{ item.materialName || '--' }}
											</u-form-item>
											<u-form-item label="规格型号" class="label-fwn form-item-6rem">
												{{ item.materialModel || '--' }}
											</u-form-item>
											<u-form-item label="材料牌号" class="label-fwn form-item-6rem">
												{{ item.materialMark || '--' }}
											</u-form-item>
											<u-form-item v-if="active!=='料头料尾'" label="额定用量"
												class="label-fwn form-item-6rem">
												{{ item.quotaQuantity?item.quotaQuantity.toFixed(2) : 0 }}
											</u-form-item>
											<u-form-item v-if="active!=='料头料尾'" label="理论用量"
												class="label-fwn form-item-6rem">
												{{ item.needQuantity || 0   }}
											</u-form-item>
											<u-form-item v-if="active!=='料头料尾'" label="当班次投料量"
												class="label-fwn form-item-6rem">
												{{ item.onDutyTotal?item.onDutyTotal.toFixed(2) : 0 }}
											</u-form-item>
											<u-form-item v-if="active!=='料头料尾'" label="前班次退料量"
												class="label-fwn form-item-6rem">
												{{ item.previousTotal?item.previousTotal.toFixed(2) : 0 }}
											</u-form-item>
											<u-form-item v-if="active!=='料头料尾'" label="当班次退料量"
												class="label-fwn form-item-6rem">
												{{ item.onPreviousDutyTotal || 0   }}
											</u-form-item>
											<u-form-item v-if="active!=='料头料尾'" label="已加料"
												class="label-fwn form-item-6rem">
												{{ item.added || 0  }}
											</u-form-item>
											<u-form-item v-if="active!=='料头料尾'" label="总投料" class="label-fwn"
												style="height: 8.5rem">
												{{ item.totalFeeding || 0  }}
											</u-form-item>
											<u-form-item v-if="active!=='料头料尾'" label="物料批次" prop="materialBatch"
												class="label-fwn">
												<InputField v-model="item.materialBatch" :maxlength="100" />
											</u-form-item>
											<u-form-item v-if="active!=='料头料尾'" label="材料牌号" class="label-fwn">
												<InputField v-model="item.brand" :maxlength="100" />
											</u-form-item>
											<u-form-item label="数量" prop="weight" required class="label-fwn">
												<!-- {{item.weight}} -->
												<InputNumberField v-model="item.weight" :decimal="3" :halfAdjust="false"
													:min="0" :max="99999999.999" />
											</u-form-item>
											<u-form-item label="单位" prop="unit" required class="label-fwn">
												<inputField v-model="item.unit" disabled />
											</u-form-item>
											<u-form-item v-if="active!=='料头料尾'" :label="active==='投料'?'出库仓库':'入库仓库'"
												prop="warehouseId" required class="label-fwn">
												<SingleSelect v-model="item.warehouseId" :list="wareHouses"
													mode="single" />
											</u-form-item>
											<u-form-item v-if="active!=='料头料尾'" label="备注" class="label-fwn">
												<InputField v-model="item.remarks" />
											</u-form-item>
										</u--form>
									</FormWrap>
								</template>
							</CheckBoxPanelGroup>
							<template slot="footer">
								<Button large @click="open2">
									历史提报记录
								</Button>
								<Button large @click="open1" type="primary" :disabled="list1.length === 0"
									:loading="submitLoading" style="margin-left: 3rem;">提交</Button>
							</template>
						</FormWrap>
					</view>
				</view>
			</Panel>
		</Content>
		<Modal :title="tipText" ref="popup1" @confirm="confirm1" />
		<Modal title="历史记录" ref="popup2" width="90%" noComfirm>
			<view class="table-demo">
				<view class="table">
					<view class="table-loading" v-if="loading">
						<u-loading-icon text="加载中" textSize="18"></u-loading-icon>
					</view>
					<view class="table-tr">
						<view class="table-th" style="width: 180px;">班次</view>
						<view class="table-th" style="width: 180px;">物料名称</view>
						<view class="table-th">方式</view>
						<view class="table-th" style="width: 200px;">批次号</view>
						<!-- <view class="table-th">状态</view> -->
						<view class="table-th" style="width: 180px;">班次日期</view>
						<view class="table-th">数量</view>
						<view class="table-th" style="width: 240px;">标签流水号</view>
						<view class="table-th">操作人</view>
						<view class="table-th" style="min-width:140px;">操作时间</view>
						<view class="table-th" style="min-width:140px;">操作</view>
					</view>
					<view class="table-tr table-empty" v-if="tableData.length === 0">
						暂无数据
					</view>
					<view class="table-tr" v-for="(item, index) in tableData" :key="index"
						v-if="tableData.length !== 0">
						<view class="table-td" style="width: 180px;">
							<view class="text-overflow-ellipsis">
								{{ item.shift || '--' }}
							</view>
						</view>
						<view class="table-td" style="width: 180px;">
							<view class="text-overflow-ellipsis">
								{{ item.materialName || '--' }}
							</view>
						</view>
						<view class="table-td">
							<view class="text-overflow-ellipsis">
								{{ item.feedingStatus }}
							</view>
						</view>
						<view class="table-td" style="width: 200px;">
							<view class="text-overflow-ellipsis">
								{{ item.materialBatch || '--' }}
							</view>
						</view>
						<!-- <view class="table-td">
		                    <view class="text-overflow-ellipsis">
		                        {{ item.status || '--' }}
		                    </view>
		                </view> -->
						<view class="table-td" style="width: 180px;">
							<view class="text-overflow-ellipsis">
								{{ item.shiftTime || '--'}}
							</view>
						</view>
						<view class="table-td">
							<view class="text-overflow-ellipsis">
								{{ item.weight || '--'}}
							</view>
						</view>
						<view class="table-td" style="width: 240px;">
							<view class="text-overflow-ellipsis">
								{{ item.tagSerialNumber || '--'}}
							</view>
						</view>
						<view class="table-td">
							<view class="text-overflow-ellipsis">
								{{ item.operator || '--'}}
							</view>
						</view>
						<view class="table-td" style="min-width: 140px;">
							<view class="text-overflow-ellipsis">
								{{ item.operatorTime || '--' }}
							</view>
						</view>
						<view class="table-td" style="display: flex;flex-direction: row;align-items: center;"
							v-if="!workInfo.cuttingPlanCode">
							<Button small text style="padding: 0;"
								v-if="item.approvalResults == '待审批' && $has('materialAdopt')"
								@click="open4(item,true)">通过</Button>
							<Button small text style="padding: 0;margin-left: 10px;"
								v-if="item.approvalResults == '待审批' && $has('materialReject')"
								@click="open4(item,false)">驳回</Button>
						</view>
					</view>
				</view>
				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pageSize" :current="pageCurrent" :total="total"
						@change="change" />
				</view>
			</view>
		</Modal>
		<Modal title="超投提醒" ref="popup3" @confirm="confirm3">
			<view class="table-tr table-empty">
				当前投料已超理论需求用量，请找班组长进行审批
			</view>
		</Modal>
		<Modal :title="viewType==false?'驳回':'通过'" ref="popup4" @confirm="confirm4">
			<InputField v-model="reasonForApproval" v-show="viewType==false" />
		</Modal>
	</Page>
</template>

<script>
	import Info from "@/components/info/index.vue";
	import Page from "@/components/page/index.vue";
	import Topbar from "@/components/topbar/index.vue";
	import Content from "@/components/content/index.vue";
	import Panel from "@/components/panel/index.vue";
	import Empty from "@/components/empty/index.vue";
	import Button from "@/components/button/index.vue";
	import CheckBoxPanelGroup from '@/components/checkboxPanelGroup/index.vue';
	import FormWrap from '@/components/formWrap/index.vue';
	import InputField from '@/components/formField/inputField/index.vue';
	import InputNumberField from '@/components/formField/inputNumberField/index.vue';
	import NumberBoxField from '@/components/formField/numberBoxField/index.vue';
	import DatePicker from '@/components/formField/datePicker/index.vue';
	import SingleSelect from '@/components/formField/singleSelect/index.vue';
	import Modal from '@/components/modal/index.vue';
	import fetch from "@/utils/fetch";
	import wmsFetch from "@/utils/wmsFetch";
	import {
		getDevice
	} from "@/store/user.js";
	import filter from "@/utils/filter";
	import {
		timeIsBetweenTimeRange
	} from "@/utils/date";

	export default {
		components: {
			Page,
			Topbar,
			Content,
			Panel,
			Info,
			Empty,
			Button,
			CheckBoxPanelGroup,
			FormWrap,
			InputField,
			InputNumberField,
			NumberBoxField,
			DatePicker,
			Modal,
			SingleSelect
		},
		data() {
			return {
				reasonForApproval: '', //驳回原因
				viewType: false,
				rowId: '',
				workCode: '',
				submitLoading: false,
				workInfo: {},
				active: '投料',
				shifts: [],
				wareHouses: [],
				loading: false,
				tipText: '',
				model: {
					shiftTime: '',
					shift: '',
					num1: '',
				},
				tableData: [{}, {}],
				total: 0,
				pageSize: 10,
				pageCurrent: 1,
				list1: [],
				rules: {
					'shiftTime': {
						type: 'number',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
					'shiftId': {
						type: 'string',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
					'weight': {
						type: 'number',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
					'unit': {
						type: 'string',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
					'shiftId': {
						type: 'number',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
					'warehouseId': {
						type: 'number',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
				},
				isResult: false,
				activeUrl: '',
			}
		},
		methods: {
			open4(row, type) {
				this.rowId = row.id;
				this.viewType = type;
				this.$refs.popup4.open()
			},
			confirm4() {
				if (this.viewType == false && !!this.reasonForApproval == false) {
					this.$toast("请输入驳回原因");
					return;
				}
				fetch('post', '/dms/materialOperation/materialApproval', null, {
					id: this.rowId,
					reasonForApproval: this.reasonForApproval,
					status: this.viewType ? '成功' : '失败',
				}).then((res) => {
					this.getData(1);
				});
			},
			tabClick(item) {
				this.active = item;
			},
			open2() {
				this.getData(1);
				this.$refs.popup2.open()
			},
			change(e) {
				this.getData(e.current)
			},
			// 获取数据
			getData(pageCurrent, value = '') {
				this.loading = true
				this.pageCurrent = pageCurrent
				// const workCode = 1100000486001;
				const workCode = this.workCode;
				fetch('post', '/dms/mobileEnd/queryMaterialOperationRecordList', null, {
					pageSize: this.pageSize,
					pageNum: this.pageCurrent,
					workCode,
				}).then((res) => {
					this.loading = false;
					this.tableData = res.records;
					this.total = res.total;
				});
			},
			getParamList() {
				const selections = this.$refs['checkboxPanelGroup'].getSelections();
				const paramList = selections.map((item) => {
					const shift = this.shifts.find(item1 => item1.value === this.model.shiftId).label;
					const warehouse = this.wareHouses.find(item1 => item1.value === item.warehouseId).label;
					return {
						feedingStatus: this.active,
						workCode: this.workCode,
						materialCode: item.materialCode,
						materialBatch: item.materialBatch,
						shiftId: this.model.shiftId,
						shift,
						shiftTime: this.dayjs(this.model.shiftTime).format('YYYY-MM-DD'),
						weight: item.weight,
						warehouseId: item.warehouseId,
						warehouse,
						brand: item.brand,
						remarks: item.remarks,
						unit: item.unit,
						tagSerialNumber: item.materialCode == this.searchMaterialCode ? this.labelNo : null,
					}
				});
				return paramList;
			},
			open1() {
				this.$refs['uForm'].validate().then((valid) => {
					const selections = this.$refs['checkboxPanelGroup'].getSelections();
					if (selections.length === 0) return this.$toast('请选择一条数据');
					this.submitLoading = true;
					const validArr = [];
					selections.forEach((item, index) => {
						this.$refs['uForm' + item.id].validate().then((valid) => {
							validArr.push(valid);
						}).catch(() => {
							validArr.push(false);
						});
					});
					// 校验物料是否正确
					const paramList = selections.map(item => {
						return {
							workCode: this.workCode,
							materialCode: item.materialCode,
							batchNumber: item.materialBatch || ' ',
						}
					});
					const that = this;
					this.tipText = '确认提交吗？';
					fetch('post', '/dms/materialOperation/queryMaterialLimitation', null, paramList).then((
						res) => {
						that.submitLoading = false;
						if (res.includes(1)) {
							return that.$toast('禁止挪用投料')
						} else if (res.includes(2)) {
							this.tipText = '该投料订单与当前生产订单无关'
						}
						setTimeout(() => {
							const pass = validArr.filter((item) => item).length === validArr
								.length;
							if (pass) {
								that.$refs.popup1.open();
							}
						}, 280);
					});
				}).catch(() => {});
			},
			async confirm1() {
				const paramList = this.getParamList();
				let isZero = false;
				for (var i = 0; i < paramList.length; i++) {
					if (paramList[i] == null || paramList[i] == 0 || paramList[i] == 'undefined') {
						isZero = true;
					}
				};
				if (isZero) {
					this.$toast('数量不能为0或空');
					return;
				}
				this.activeUrl = this.active === '投料' ? '/dms/mobileEnd/addMaterialOperation' :
					this.active === '退料' ? '/dms/mobileEnd/updateMaterialOperation' :
					'/dms/materialHeadTail/saveMaterialHeadTail';
				// console.log('url:'+url)
				// console.log('data:',JSON.stringify(paramList))
				if (this.active == '投料') {
					this.isResult = await this.queryMaterialApproval(paramList)
					if (this.isResult) {
						this.$refs.popup3.open()
					} else this.confirm3();
				} else this.confirm3();
			},
			confirm3() {
				var that = this;
				const data = this.getParamList().map(item => {
					if (this.active == '料头料尾') {
						return {
							materialCode: item.materialCode,
							quantity: item.weight,
							shift: item.shift,
							shiftId: item.shiftId,
							unit: item.unit,
							workCode: item.workCode,
							shiftTime: this.dayjs(this.model.shiftTime).format('YYYY-MM-DD'),
						}
					} else {
						return {
							...item,
							isResult: this.isResult,
						}
					}
				});
				fetch('post', this.activeUrl, null, data).then(() => {
					this.$toast('操作成功');
					setTimeout(function() {
						uni.redirectTo({
							url: 'index?workCode=' + that.workCode
						})
					}, 1500);
					// uni.navigateBack()
				});
			},
			async queryMaterialApproval(data) {
				// const paramList = data.map(item => {
				// 	return {
				// 		materialCode: item.materialCode,
				// 		workCode: item.workCode
				// 	}
				// })
				// const res = await fetch('post', '/dms/materialOperation/queryMaterialApproval', null, paramList)
				// return res;
				return false;
			},
			goto(url) {
				uni.redirectTo({
					url,
					animationType: "pop-in",
					animationDuration: 1000,
				})
			},
			getWorkOrderInfo() {
				fetch('get', '/dms/mobile/selectWorkByWorkCode', {
					workCode: this.workCode,
				}).then((res) => {
					this.workInfo = res;
				});
			},
			scanCode(result) {
				const that = this;
				const info = result.split(';');
				//info[0] 场景 scene_01 MES自有码
				//info[1] 标签流水号
				//info[2] 物料编号
				//info[3] 生产数量
				//info[4] 批次号
				//info[5] 材料牌号
				this.labelNo = info[1]
				if (info[0] === 'scene_01') {
					let result = false;
					fetch('get', '/dms/labelPrinting/getLabelInfoBySerial', {
						tagSerial: this.labelNo,
					}).then(res => {
						if (res == null) {
							this.$toast('无标签数据')
							return false;
						}
						this.searchMaterialCode = res.materialCode;
						this.list1.forEach((item, index) => {
							if (item.materialCode === res.materialCode) {
								let data = {
									...item
								}
								result = true;
								data.selected = true;
								data.weight = res.residueNumber;
								data.materialBatch = res.batchNumber;
								data.brand = res.materialMark;
								this.$set(this.list1, index, data);
								// 测试滚动
								that.$refs['checkboxPanelGroup'].changeRightTitle(index);
							}
						});
						if (result == false) {
							this.$toast('物料不匹配')
						}
					})
				} else {
					wmsFetch('post', '/warehouseService/getStockOutLabel', null, {
						corpId: 'hx',
						data: {
							serialNo: info[0]
						}
					}).then((res) => {
						if (res && res.length !== 0) {
							let result = false;
							const data = res[0];
							this.list1.forEach((item, index) => {
								if (item.materialCode === data.materialCode) {
									let setData = {
										...item
									}
									setData.selected = true;
									setData.weight = data.labelQty || 0;
									setData.materialBatch = data.batchNo || '';
									if (data.batchProp) {
										setData.brand = data.batchProp.prop_CLPH;
									}
									result = true;
									this.$set(this.list1, index, setData);
									that.$refs['checkboxPanelGroup'].changeRightTitle(index);
								}
							});
							if (result == false) {
								this.$toast('物料不匹配')
							}
						}
					});
				}
			},
			shiftTimeChange(val) {
				this.model.shiftId = null;
				this.getShiftList(val);
			},
			getShiftList(shiftTime) {
				fetch("get", "/dms/mobile/getShiftList", {
					deviceNo: getDevice().deviceNo,
					shiftDate: shiftTime ? this.dayjs(shiftTime).format('YYYY-MM-DD') : '',
				}).then((res) => {
					this.shifts = res.map((item) => ({
						label: item.shift,
						value: item.id,
						id: item.id,
						scheduleDate: item.scheduleDate,
					}));
					if (this.shifts.length !== 0) {
						const has = res.find(item => timeIsBetweenTimeRange(filter.formatCurrentTimeDuration(),
							item.shiftStartTime,
							item.shiftEndTime));
						if (has)
							this.model.shiftId = has.shiftId;
						else
							this.model.shiftId = this.shifts[0].value;
						if (!shiftTime) {
							this.model.shiftId = this.shifts[0].value;
							this.model.shiftTime = this.dayjs(this.shifts[0].scheduleDate).valueOf();
						}
					}
					this.getList1()
				});
			},
			getWareHouses() {
				fetch("get", "/dms/mobileEnd/getUseWarehouse", {
					deviceNo: getDevice().deviceNo,
				}).then((res) => {
					if (res) {
						this.wareHouses = [{
							label: res.backupName,
							value: res.id,
						}];
						this.list1.forEach((item, index) => {
							item.warehouseId = this.wareHouses[0].value;
							this.$set(this.list1, index, item);
						});
					}
				});
			},
			shiftChange(val) {
				this.getList1()
			},
			getList1() {
				const {
					workCode
				} = this;
				const id = this.shifts.find(item1 => item1.value === this.model.shiftId).id;
				fetch('get', '/dms/mobileEnd/getMaterialAddList', {
					pageNum: 1,
					pageSize: 50,
					workCode,
					shiftId: id,
				}).then((res) => {
					this.list1 = res.records;
					this.getWareHouses();
				});
			}
		},
		mounted() {
			// setTimeout(()=>{
			// 	this.scanCode('scene_01;LEZ9RB7dbE9FBd')
			// },4000)
		},
		onLoad(params) {
			this.workCode = params.workCode
			this.getShiftList();
			this.getWorkOrderInfo();
		},
	};
</script>

<style scoped lang="scss">
	.left {
		flex: 0 auto;
		width: 50rem;
		background: #f8f8fa;
	}

	.right {
		flex: 1;
		background: #fff;
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		padding: 2rem 6rem 0;

		/deep/ .form-wrap .body {
			padding-top: 0 !important;
			flex: 1;
		}
	}

	.tab_box {
		display: flex;
		flex-direction: column;
		padding-right: 2rem;
		margin-right: 2rem;
		width: 27rem;
		height: 64vh;
		overflow-y: auto;


		.tab_btn {
			display: flex;
			justify-content: center;
			align-items: center;
			border-radius: 1rem;
			height: 8rem;
			width: 100%;
		}

		.active {
			background-color: #ecf1f5;
			color: #0076cc;
			height: 8rem;
			width: 100%;
		}
	}

	.content_box {
		flex: 1;
		display: flex;
		flex-direction: column;
		height: 100%;

		.content {
			flex: 1;
			display: none;
			animation: moving .5s ease;
			overflow-y: scroll;
			display: grid;
			grid: auto-flow / 1fr 1fr 1fr 1fr;
		}

		.active {
			display: block;
		}
	}

	.label-fwn {
		/deep/ .u-form-item__body__left__content__label {
			font-weight: normal !important;
		}
	}

	.form-item-6rem {
		height: 6.5rem;
	}

	.table-demo {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.table {
		display: flex;
		flex-direction: column;
		border: 1px solid #ecf0f2;
		border-radius: 2rem;
		overflow-x: scroll;
		position: relative;

		.table-loading {
			position: absolute;
			top: 0;
			right: 0;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			background: rgba(255, 255, 255, 0.8);
		}

		.table-empty {
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 4rem 0;
			font-size: 2rem;
		}

		.table-tr {
			display: flex;
			flex-direction: row;
		}

		.table-th {
			// flex: 1;
			min-width: 120px;
			background: #edf1f3;
			font-size: 2rem;
			text-align: center;
			padding: 2rem 0;
			overflow: hidden;
		}

		.table-td {
			// flex: 1;
			min-width: 120px;
			font-size: 2rem;
			text-align: center;
			padding: 2rem 0;
			overflow: hidden;
			border-top: 1px solid #ecf0f2;
		}

		.text-overflow-ellipsis {
			width: 80%;
			padding: 0;
			text-overflow: ellipsis;
			overflow: hidden;
			white-space: nowrap;
			margin: 0 auto;
		}
	}

	/deep/ .uni-pagination-box {
		display: flex;
		justify-content: flex-end;
		margin-top: 2rem;
		font-size: 2rem;

		.uni-pagination__total {
			font-size: 2rem;
		}

		.uni-pagination__btn {
			font-size: 2rem;
		}

		.uni-pagination__num {
			font-size: 2rem;
		}

		.uni-pagination__num-tag {
			width: 6rem;
		}
	}
</style>